<?php
namespace Shortener;

define('SINA_APPKEY', '777622521');

class Weibo
{
    public function shorten($long_url)
    {
        $url = 'http://api.t.sina.com.cn/short_url/shorten.json?source=' . SINA_APPKEY . '&url_long=' . urlencode($long_url);
        $result = $this->_curlRequest($url);
        $json = json_decode($result);

        // 异常情况返回false
        if (isset($json->error) or !isset($json[0]->url_short) or $json[0]->url_short == '') {
            return false;
        } else {
            return $json[0]->url_short;
        }
    }

    public function expand($short_url)
    {
        $url = 'http://api.t.sina.com.cn/short_url/expand.json?source=' . SINA_APPKEY . '&url_short=' . urlencode($short_url);
        $result = $this->_curlRequest($url);
        $json = json_decode($result);

        // 异常情况返回false
        if (isset($json->error) or !isset($json[0]->url_long) or $json[0]->url_long == '') {
            return false;
        } else {
            return $json[0]->url_long;
        }
    }

    function _curlRequest($url)
    {
        $addHead = array(
            "Content-type: application/json"
        );

        $curl_obj = curl_init();
        curl_setopt($curl_obj, CURLOPT_URL, $url);
        curl_setopt($curl_obj, CURLOPT_HTTPHEADER, $addHead);
        curl_setopt($curl_obj, CURLOPT_HEADER, 0);
        curl_setopt($curl_obj, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_obj, CURLOPT_TIMEOUT, 8);
        $result = curl_exec($curl_obj);
        curl_close($curl_obj);

        return $result;
    }

}


// end